import datetime
import json
import math
import os
import pickle
import platform
import time
import sys

from src.utils.LogUtils import Logger

logger = Logger()


def cleanScreen():
    """
    清屏
    :return:
    """
    # PyCharm开发中，不清屏
    if "PYCHARM_HOSTED" in os.environ:
        return
    if platform.system().lower() == "windows":
        os.system("cls")
    else:
        os.system("clear")


def save_dump(file, objData):
    """
    保存Python对象为文件
    """
    with open(file, "wb") as f:
        pickle.dump(objData, f, protocol=2)


def load_dump(file):
    """
    加载dump文件
    """
    if os.path.exists(file):
        try:
            with open(file, "rb") as f:
                return pickle.load(f)
        except Exception as e:
            # Nothing to do
            print(e)

    return None


def load_json(file):
    """
    加载json文件
    """
    if os.path.exists(file):
        try:
            with open(file, encoding="utf8") as f:
                return json.load(f)
        except Exception as e:
            # Nothing to do
            print(e)
    return None


def removeFile(file):
    try:
        if os.path.exists(file):
            os.remove(file)
    except Exception as e:
        print("删除文件发生异常。 %s" % file, e)


def createColorText(text: str, color: str):
    """
    :param text: 文字
    :param color: 文字颜色 red,green,yellow,blue
    :return:
    """
    colorMap = {"red": "31", "green": "32", "yellow": "33", "blue": "34"}
    displayColor = colorMap[color] if color in colorMap.keys() else 37
    return "\033[0;%sm%s\033[0m" % (displayColor, text)


def strToDate(s, fmt="%Y%m%d"):
    try:
        return datetime.datetime.strptime(s, fmt).date()
    except:
        return None


def DateToStr(s, fmt="%Y%m%d"):
    try:
        return datetime.datetime.strftime(s, fmt)
    except:
        return None


def DateToYMDHMS(s, fmt="%Y-%m-%d %H:%M:%S"):
    try:
        return datetime.datetime.strftime(s, fmt)
    except:
        return None


def statisticsTime(start, content: str):
    cast = (time.perf_counter() - start)
    m = math.floor(cast / 60)
    s = cast - m * 60
    logger.info(content+ '总耗时: %d分%.3f秒' % (m, s))


@staticmethod
def __getProperty__(dicData: dict, key: str) -> any:
    if dicData is None:
        return None
    if key not in dicData.keys():
        return None
    return dicData[key]


def strToNum(str):
    if str is None or str == '':
        return None
    if str.__contains__(":"):
        return None
    try:
        return float(str)
    except Exception as e:
        return None


def getProperty(dicData: dict, key: str, defValue=None, exceptionWhenKeyNotFound=False) -> any:
    if dicData is None:
        return defValue
    if key not in dicData.keys():
        if exceptionWhenKeyNotFound:
            raise Exception("Key [%s] not found" % key)
        else:
            return defValue
    return dicData[key]


def isCommandParam(argparse, commandParam):
    try:
        for command in argparse[1:]:
            if command.__contains__(commandParam):
                return {"exist": True,
                        "value": command.replace("-", "", 2).replace("=", "", 1).replace(commandParam, "", 2)}
        return {"exist": False}
    except SystemExit as e:
        return {"exist": False}


def existCommandParam(obj, param):
    return param.exist


def progress_bar(finish_tasks_number, tasks_number):
    """
    进度条

    :param finish_tasks_number: int, 已完成的任务数
    :param tasks_number: int, 总的任务数
    :return:
    """

    percentage = round(finish_tasks_number / tasks_number * 100)
    print("\r进度: {}%: ".format(percentage), "▓" * (percentage // 2), end="")
    sys.stdout.flush()
